<?php

namespace app\common\service\shop;

use Exception;
use think\admin\extend\HttpExtend;
use think\exception\ValidateException;

/**
 * OzonService
 * @Description Ozon(报表)接口服务
 * @docs https://docs.ozon.ru/api/seller/zh/?abt_att=1#tag/Introduction
 * @author shirukun
 * @date 2024-12-13
 */
class OzonReport
{
    // api接口地址
    protected $api_url = "https://api-seller.ozon.ru";

    // 配置
    protected $config = [
        'client_id' => '',
        'api_key' => '',
    ];

    /**
     * 错误信息
     */
    public $err;

    /**
     * 获取错误信息
     * @return array
     */
    public function getErr()
    {
        return $this->err;
    }

    /**
     * @throws Exception
     */
    public function __construct($config = [])
    {
        $this->config = array_merge($this->config, $config);
        try {
            validate([
                'client_id' => 'require',
                'api_key' => 'require',
            ], [
                'client_id.require' => 'ozon配置用户识别号不存在',
                'api_key.require' => 'ozon配置api-秘钥不存在',
            ])->check($this->config);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
//            Log::record($e->getMessage(), 'export');
            throw new Exception($e->getMessage());
        }
    }

    /**
     * Desc: （报告）财务报告
     * @docs https://docs.ozon.ru/api/seller/zh/?abt_att=1#operation/FinanceAPI_FinanceCashFlowStatementList
     * @param $where
     * @return array
     */
    public function finance_cash_flow_statement($where = [], $page_size = 1, $page = 1, $with_details = true)
    {
        $params = [
            "date" => [ // 报告期限。 $where
                "from" => "2022-01-01T00:00:00.000Z", // 计算报告的起始日期。
                "to" => "2022-12-31T00:00:00.000Z" // 计算报告的停止日期。
            ],
            "with_details" => $with_details, // true，如果需要在响应中添加附加参数。
            "page" => $page, // 页码
            "page_size" => $page_size // 页条数
        ];

        $params['date']['from'] = date('c', strtotime(date('Y/m/d 00:00:00')));
        $params['date']['to'] = date('c', strtotime(date('Y/m/d 23:59:59')));
        $params['date']['from'] = substr($params['date']['from'], 0, -6) . '.000Z';
        $params['date']['to'] = substr($params['date']['to'], 0, -6) . '.000Z';

        $params['date'] = array_merge( $params['date'], $where);
        //Log::record($params,'test');
//        halt($params);

        $res = HttpExtend::post($this->api_url . '/v1/finance/cash-flow-statement/list', json_encode($params, '320'), ['headers' => ['Content-Type:application/json', 'Client-Id:' . $this->config['client_id'], 'Api-Key:' . $this->config['api_key']]]);
        $res = json_decode($res, true);
            //Log::record($orderData,'test');
//        halt($res);

        if(empty($res)){
            $this->err = '网络错误';
            return ['code' => 0, 'data' => []];
        }

        if(isset($res['code'])){
            $this->err = $res['message'];
            return ['code' => 0, 'data' => []];
        }

        return ['code' => 1, 'data' => $res['result']];
    }

    /**
     * Desc: （财务报告）交易清单
     * @docs https://docs.ozon.ru/api/seller/zh/?abt_att=1#operation/FinanceAPI_FinanceTransactionListV3
     * @param $where
     * @return array
     */
    public function finance_transaction_list($where = [], $page_size = 1, $page = 1, $with_details = true)
    {
        $params = [
            "filter" =>[ // $where 过滤器。
//                "date" => [ // 报告期限。
//                    "from" => "2022-01-01T00:00:00.000Z", // 计算报告的起始日期。
//                    "to" => "2022-12-31T00:00:00.000Z" // 计算报告的停止日期。
//                ],
//                "operation_type" => [], // 交易类型 详细请看文档
//                "posting_number" => "", // 发货号
//                // 收费类型 all — 所有, orders — 订单, returns — 退货和取消, services — 服务费,compensation — 补贴,transferDelivery — 运费,other — 其他。
//                "transaction_type" => "all",
            ],
            "page" => $page, // 页码
            "page_size" => $page_size // 页条数
        ];

        $params['filter']['date']['from'] = date('c', strtotime(date('Y/m/d 00:00:00')));
        $params['filter']['date']['to'] = date('c', strtotime(date('Y/m/d 23:59:59')));
        $params['filter']['date']['from'] = substr($params['filter']['date']['from'], 0, -6) . '.000Z';
        $params['filter']['date']['to'] = substr($params['filter']['date']['to'], 0, -6) . '.000Z';

        $params['filter'] = array_merge( $params['filter'], $where);
        //Log::record($params,'test');
//        halt($params);

        $res = HttpExtend::post($this->api_url . '/v3/finance/transaction/list', json_encode($params, '320'), ['headers' => ['Content-Type:application/json', 'Client-Id:' . $this->config['client_id'], 'Api-Key:' . $this->config['api_key']]]);
        $res = json_decode($res, true);
            //Log::record($orderData,'test');
//        halt($res);

        if(empty($res)){
            $this->err = '网络错误';
            return ['code' => 0, 'data' => []];
        }

        if(isset($res['code'])){
            $this->err = $res['message'];
            return ['code' => 0, 'data' => []];
        }

        return ['code' => 1, 'data' => $res['result']];
    }
}